package cn.catsdad.base.repository.impl;

import cn.catsdad.base.page.PageBean;
import cn.catsdad.base.page.PageParam;
import cn.catsdad.base.repository.api.ICommonRepository;
import cn.catsdad.constant.iConstant.ICommonWarningType;
import cn.catsdad.util.StringUtil;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;

/**
 * 通用repository默认bean
 *
 * @author xuyl
 * @version V1.0.0 2024/7/8
 * @since V100R001
 */
@Component
@SuppressWarnings(ICommonWarningType.UNCHECKED)
public class CommonRepositoryImpl<T> implements ICommonRepository<T> {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void pageQuery(PageBean<T> page, PageParam param) {
        String query = page.getQuery();
        if (StringUtil.isNotEmpty(query)) {
            //查询分页数据
            doPageQuery(page, param);
            //查询数据总数
            doPageCount(page, param);
        }
    }

    /**
     * 分页查询
     *
     * @param page  分页参数
     * @param param 查询参数
     */
    private void doPageQuery(PageBean<T> page, PageParam param) {
        StringBuilder sql = new StringBuilder(page.getQuery());
        sql.append(" ").append(param.createWhereContent()).append(" ");
        List<Map<String, String>> orderBy = page.getOrderBy();
        if (StringUtil.isNotEmpty(orderBy)) {
            sql.append(" order by ");
            for (Map<String, String> entry : orderBy) {
                if (StringUtil.isNotEmpty(entry)) {
                    for (Map.Entry<String, String> stringEntry : entry.entrySet()) {
                        sql.append(stringEntry.getKey()).append(" ").append(stringEntry.getValue()).append(",");
                    }
                }
            }
            if (StringUtil.isNotEmpty(orderBy)) {
                sql.setLength(sql.length() - 1);
                sql.append(" ");
            }
        }
        Query query = entityManager.createQuery(sql.toString());
        query.setFirstResult((page.getPage() - 1) * page.getSize());
        query.setMaxResults(page.getSize());
        for (Map.Entry<String, Object> entry : param.getParamMap().entrySet()) {
            query.setParameter(entry.getKey(), entry.getValue());
        }
        page.setQueryResult(query.getResultList());
    }

    /**
     * 分页count
     *
     * @param page  分页参数
     * @param param 查询参数
     */
    private void doPageCount(PageBean<T> page, PageParam param) {
        StringBuilder sql = new StringBuilder(page.getQuery());
        int fromIndex = sql.indexOf("from");
        sql.replace(0, fromIndex, "select count(1) ");
        sql.append(param.createWhereContent());
        Query query = entityManager.createQuery(sql.toString());
        Map<String, Object> paramMap = param.getParamMap();
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            query.setParameter(entry.getKey(), entry.getValue());
        }
        Object count = query.getSingleResult();
        if (count != null) {
            page.setTotal(Integer.parseInt(count.toString()));
        }
    }

}
